package com.syni.mdd.sjb.community.base.controller.protect;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxCompany;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.community.base.annotion.AdminAuthVerification;
import com.syni.mdd.sjb.community.base.config.QywxThirdApiProperties;
import com.syni.mdd.sjb.community.base.entity.vo.rp.common.SettingRpVo;
import com.syni.mdd.sjb.community.base.entity.vo.rp.common.WxConfigRpVo;
import com.syni.mdd.sjb.community.base.entity.vo.rq.WxConfigVo;
import com.syni.mdd.sjb.community.base.service.CommonUtilsServce;
import com.syni.mdd.sjb.community.base.service.SjbQywxCompanyService;
import com.syni.mdd.sjb.community.base.utils.OAUtils;
import com.syni.mdd.sjb.community.base.utils.WebChatUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/common")
@Log4j2
public class CommonController {

    @Autowired
    QywxThirdApiProperties qywxThirdApiProperties;

    @Autowired
    CommonUtilsServce commonUtilsServce;

    @Autowired
    SjbQywxCompanyService sjbQywxCompanyService;


    @PostMapping("/setting")
    public Map<String, Object> setting() {
        SettingRpVo settingRpVo = new SettingRpVo();
        settingRpVo.setLoginUrl(commonUtilsServce.getLoginUrl());
        settingRpVo.setRegisterUrl(commonUtilsServce.getRegisterUrl());
        settingRpVo.setAuthorizationUrl(commonUtilsServce.getInstallUrl());
        settingRpVo.setGuidePageUrl(commonUtilsServce.getGuidePageUrl());
        return ResultMapHelper.success(settingRpVo);
    }

    @PostMapping("/wxConfig")
    @AdminAuthVerification
    public Map<String, Object> wxConfig(@RequestBody WxConfigVo wxConfigVo) {
        WxConfigRpVo wxConfigRpVo = new WxConfigRpVo();
        SjbQywxCompany sjbQywxCompany = sjbQywxCompanyService.getByCompanyId(wxConfigVo.getCorpid());
        if(sjbQywxCompany == null){
            return ResultMapHelper.success(wxConfigRpVo);
        }
        String jsapiTicket = OAUtils.getSuiteJsapiTicket(sjbQywxCompany.getCorpId(),sjbQywxCompany.getPermanentCode());
        Map<String,String> retMap = WebChatUtils.sign(jsapiTicket,wxConfigVo.getJssdkUrl());
        wxConfigRpVo = JSON.parseObject(JSON.toJSONString(retMap),WxConfigRpVo.class);
        wxConfigRpVo.setCorpid(sjbQywxCompany.getCorpId());
        wxConfigRpVo.setAgentid(sjbQywxCompany.getAgentId());
        return ResultMapHelper.success(wxConfigRpVo);
    }
}
